package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    //员工登录
    @Override
    public Map checkLogin(Employee employee) {
        Map resultMap = new HashMap();
        //-1- 先查名称   select * from employee where username=?
        LambdaQueryWrapper<Employee> qwr = new LambdaQueryWrapper<>();
        qwr.eq(Employee::getUsername,employee.getUsername());
        Employee selectOne = employeeMapper.selectOne(qwr);//单条数据对象

        //-2- 查不到名字 返回msg
        if(selectOne==null){
            resultMap.put("msg","用户名不存在");
            return resultMap;
        }

        //-3- 加密：密码
        int FF=2; //   “1”=Md5加密   “2”=Bcrypt(加盐加密)
        boolean equals_password_result=false;
        if(FF==1){
            //Md5加密   明文：12345 数据表密文：e10adc3949ba59abbe56e057f20f883e
            String PassCode = MD5Utils.code(employee.getPassword());
            equals_password_result = PassCode.equals(selectOne.getPassword());
        }else {
            //Bcrypt(加盐加密)--matches方法_可以把原数据直接_和密文比较
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            equals_password_result = passwordEncoder.matches(employee.getPassword(), selectOne.getPassword());
        }
        //----------匹配数据库:true 相同，false不同
        log.info("[》》》EmployeeServiceImpl--{}加密]:--密码匹配结果 {}",FF==1?"Md5":"Bcrypt",equals_password_result);
        if(!equals_password_result){
            resultMap.put("msg","密码输入有误");
            return resultMap;
        }

        //-4-判断用户的状态是否启动（status=0 账号禁用）
        if(selectOne.getStatus()==0){
            resultMap.put("msg","账户被禁用");
            return resultMap;
        }
        //-5-登录成功
        resultMap.put("employee",selectOne);
        return resultMap;
    }


    //员工登录----模型不可用
    public Map checkLogin_MD5(Employee employee) {
        Map resultMap = new HashMap();
        //1. 查询数据表employee,查询指定的用户名称是否存在
        //select * from employee where username=?
        LambdaQueryWrapper<Employee> qwr = new LambdaQueryWrapper<>();
        qwr.eq(Employee::getUsername,employee.getUsername());
        Employee selectOne = employeeMapper.selectOne(qwr);//数据库对象
        if(selectOne==null){
            resultMap.put("msg","用户名不存在");
            return resultMap;
        }
        //2. 如果查询到，用户信息存在
        //校验用户密码是否正确：Md5加密 / Bcrypt(加盐加密)
        //用户输入的明文：12345   和数据表中查询到的密文：e10adc3949ba59abbe56e057f20f883e
        String PassCode = MD5Utils.code(employee.getPassword());
        boolean equals = PassCode.equals(selectOne.getPassword());
        log.info("[》》》EmployeeServiceImpl--Md5加密]:--密码匹配 {}",equals);
        if(!equals){
            resultMap.put("msg","密码输入有误");
            return resultMap;
        }
        //3. 判断用户的状态是否启动（status=0 账号禁用）
        if(selectOne.getStatus()==0){
            resultMap.put("msg","账户被禁用");
            return resultMap;
        }
        //4. 登录成功
        resultMap.put("employee",selectOne);
        return resultMap;
    }

    //--T2-1：添加员工
    @Override
    public boolean addEmployee(Employee employee,Employee admin) {
        log.info("[》新增员工--信息]:{}",employee);
        log.info("[》新增员工--管理]:{}",admin);
        //添加-员工数据初始化--补充修改时间，修改人员
        String password="123456"; //默认密码
        String encode = new BCryptPasswordEncoder().encode(password);
        employee.setPassword(encode);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser(admin.getId()); //管理员id
//        employee.setUpdateUser(admin.getId());
        log.info("[》新增员工--预储存信息]:{}",employee);
        //--sql添加
        return employeeMapper.insert(employee)==1?true:false;
    }
    //--T2-2：分页查询----
    //page=1&pageSize=10&name=zs
    @Override
    public IPage<Employee> queryPage(Map map) {
        log.info("[》分页查询--接收Map]:{}",map);
        //--条件构造器
        LambdaQueryWrapper<Employee> qwr=new LambdaQueryWrapper<>();
        qwr.like(map.get("name")!=null && !"".equals(map.get("name")),
                Employee::getName,map.get("name"));
        //添加排序条件
        //qwr.orderByDesc(Employee::getUpdateTime);
        //执行查询
        Page<Employee> page = new Page<>(Long.parseLong((String)map.get("page")),
                Long.parseLong((String)map.get("pageSize")));
        return employeeMapper.selectPage(page,qwr);
    }

    //--T2-3:禁用账号    --T2-4:修改账号
    @Override
    public boolean updataEmployee(Employee employee, Employee admin) {
        log.info("[》修改员工--预修改信息]:{}",employee);
        log.info("[》修改员工--管理者]:{}",admin);
//        //修改信息
//        employee.setUpdateUser(admin.getId());
//        employee.setUpdateTime(LocalDateTime.now());

        //--修改
        log.info("[》修改员工--预修改信息]:{}",employee);
        return employeeMapper.updateById(employee)==1?true:false;
    }

    //--T2-4-1：id查找
    @Override
    public Employee selectByIdEmployee(Long id) {
        log.info("[》id查找--id]:{}",id);
        return employeeMapper.selectById(id);
    }
}






